<?php

namespace backend\modules\business\controllers;

use backend\controllers\AdminController;
use common\models\business\BusinessCustomerCategory;
use common\models\business\BusinessCustomerField;
use common\models\business\BusinessCustomerFieldvalue;
use Yii;
use common\models\business\BusinessCustomer;
use backend\modules\business\models\BusinessCustomerSearch;
use yii\db\Query;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * CustomerController implements the CRUD actions for BusinessCustomer model.
 */
class CustomerController extends AdminController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all BusinessCustomer models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new BusinessCustomerSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single BusinessCustomer model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new BusinessCustomer model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new BusinessCustomer();
        $cateid = Yii::$app->request->get('cateid');
        if(empty($cateid)){
            $cate = BusinessCustomerCategory::find()->asArray()->one();
            $cateid = $cate['id'];
        }
        $model->cateid = $cateid;

        if ($model->load(Yii::$app->request->post())) {
            if(!$model->save()){
                return $this->dialog($this->checkError($model));
            }
            $customerid = $model->id;

            $postdata = Yii::$app->request->post();
            foreach ($postdata as $key => $value){
                $fid = (new Query())->select('id')->from(BusinessCustomerField::tableName())->where('name=:name',[':name'=>$key])->one();
                if($fid){
                    $data = [
                        'customerid' => $customerid,
                        'fieldid' => $fid['id'],
                        'value' => $value
                    ];
                    Yii::$app->db->createCommand()->insert(BusinessCustomerFieldvalue::tableName(),$data)->execute();
                }
            }
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing BusinessCustomer model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post())) {

            $postdata = Yii::$app->request->post();

            if(!$model->save()){
                return $this->dialog($this->checkError($model));
            }
            foreach ($postdata as $key => $value){
                $fid = (new Query())->select('id')->from(BusinessCustomerField::tableName())->where('name=:name',[':name'=>$key])->one();
                if($fid){
                    $ise = Yii::$app->db->createCommand('select id from '.BusinessCustomerFieldvalue::tableName().' where customerid=:id and fieldid=:fid')
                        ->bindValues([':id'=>$id,':fid'=>$fid['id']])->queryOne();
                    $data = [
                        'customerid' => $id,
                        'fieldid' => $fid['id'],
                        'value' => $value
                    ];
                    if(!$ise){
                        Yii::$app->db->createCommand()->insert(BusinessCustomerFieldvalue::tableName(),$data)->execute();
                    }else{
                        Yii::$app->db->createCommand()->update(BusinessCustomerFieldvalue::tableName(),$data,'customerid=:id and fieldid=:fid',[':id'=>$id,':fid'=>$fid['id']])
                            ->execute();
                    }
                }
            }

            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing BusinessCustomer model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the BusinessCustomer model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return BusinessCustomer the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = BusinessCustomer::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
